Passed
Push — master ( 17fae3...e5a7e5 )
by Jesús
02:17
created

keyboard.ts ➔ handleArrowDown   A

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
1
import { elements } from '../../bip39';
2
import {
3
  getSelectedIndex,
4
  setSelectedIndex,
5
  updateSuggestionSelection,
6
  clearSuggestionSelection,
7
  hideSuggestions,
8
} from './suggestions';
9
10
export function handleKeydown(e: KeyboardEvent, onSelectWord: (word: string) => void): void {
11
  const suggestions = elements.wordSuggestions.querySelectorAll('.suggestion-item');
12
13
  if (suggestions.length === 0) return;
14
15
  switch (e.key) {
16
    case 'ArrowDown':
17
      e.preventDefault();
18
      handleArrowDown(suggestions);
19
      break;
20
21
    case 'ArrowUp':
22
      e.preventDefault();
23
      handleArrowUp(suggestions);
24
      break;
25
26
    case 'Enter': {
27
      e.preventDefault();
28
      handleEnterKey(suggestions, onSelectWord);
29
      break;
30
    }
31
32
    case 'Escape':
33
      e.preventDefault();
34
      handleEscapeKey();
35
      break;
36
  }
37
}
38
39
function handleArrowDown(suggestions: NodeListOf<Element>): void {
40
  const currentIndex = getSelectedIndex();
41
  const newIndex = Math.min(currentIndex + 1, suggestions.length - 1);
42
  setSelectedIndex(newIndex);
43
  updateSuggestionSelection(suggestions);
44
}
45
46
function handleArrowUp(suggestions: NodeListOf<Element>): void {
47
  const currentIndex = getSelectedIndex();
48
  const newIndex = Math.max(currentIndex - 1, 0);
49
  setSelectedIndex(newIndex);
50
  updateSuggestionSelection(suggestions);
51
}
52
53
function handleEnterKey(suggestions: NodeListOf<Element>, onSelectWord: (word: string) => void): void {
54
  const currentIndex = getSelectedIndex();
55
  if (currentIndex >= 0) {
56
    const selectedItem = suggestions[currentIndex] as HTMLElement;
57
    const wordSpan = selectedItem.querySelector('.suggestion-word');
58
    const word = wordSpan?.textContent;
59
    if (word) {
60
      onSelectWord(word);
61
      hideSuggestions();
62
    }
63
  }
64
}
65
66
function handleEscapeKey(): void {
67
  hideSuggestions();
68
  clearSuggestionSelection();
69
}
70